package com.medical.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.medical.dao.AreaMapper;
import com.medical.dao.InstructorMapper;
import com.medical.dao.ServiceCenterMapper;
import com.medical.entity.Area;
import com.medical.entity.Callout;
import com.medical.entity.Instructor;
import com.medical.entity.Markers;
import com.medical.entity.ResultBean;
import com.medical.entity.ServiceCenter;
import com.medical.service.ServiceCenterService;
import com.medical.util.MapUtils;

@Service
@Transactional
public class ServiceCenterServiceImpl implements ServiceCenterService {
	Logger logger = LoggerFactory.getLogger(ServiceCenterServiceImpl.class);

	@Resource
	private ServiceCenterMapper serviceCenterMapper;

	@Resource
	private InstructorMapper instructorMapper;

	@Resource
	private AreaMapper areaMapper;

	@Override
	public Map<String, Object> query(String name, int areaId, int pageIndex, Map<String, Object> map) {
		// TODO Auto-generated method stub
		int size = 10;
		name = "%" + name + "%";
		List<Map<String, Object>> data = serviceCenterMapper.getListByPage(name, areaId, (pageIndex - 1) * size, size);

		List<Area> areaList = areaMapper.selectList(new EntityWrapper<Area>());
		map.put("areaList", areaList);

		// 获取总条数，并释放资源
		int total = serviceCenterMapper.getListCount(name, areaId);
		map.put("data", data);
		map.put("pageIndex", pageIndex);
		int totalPages = (total - 1) / size + 1;
		map.put("totalPages", totalPages);
		map.put("total", total);
		return map;
	}

	@Override
	public Map<String, Object> toAdd(Map<String, Object> map) {
		List<Area> areaList = areaMapper.selectList(new EntityWrapper<Area>());
		map.put("areaList", areaList);
		return map;

	}

	@Override
	public int add(ServiceCenter serviceCenter, String path, String[] instructors, String[] levels) {
		// TODO Auto-generated method stub
		try {
			int count = 0;
			List<ServiceCenter> list = serviceCenterMapper.selectList(new EntityWrapper<ServiceCenter>().eq("name", serviceCenter.getName()));
			if (list != null && list.size() > 0) {
				count = -1;
			}
			if (list == null || list.size() == 0) {
				serviceCenter.setImgUrl(path);
				serviceCenter.setCreateTime(new Date());
				count = serviceCenterMapper.insert(serviceCenter);

				if (count > 0) {
					for (int i = 0; i < instructors.length; i++) {
						Instructor instructor = new Instructor();
						instructor.setName(instructors[i]);
						instructor.setLevel(levels[i]);
						instructor.setServiceId(serviceCenter.getId());
						int cou = instructorMapper.insertSelective(instructor);
						if (cou > 0) {
							count++;
						}
					}
				}
			}
			return count;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.info("服务中心增加：" + e.getMessage());
			return 0;
		}
	}

	@Override
	public Map<String, Object> detail(int id, Map<String, Object> map) {
		// TODO Auto-generated method stub
		try {
			ServiceCenter serviceCenter = serviceCenterMapper.selectById(id);
			List<Instructor> instructorList = instructorMapper.selectList(new EntityWrapper<Instructor>().eq("service_id", id));
			List<Area> areaList = areaMapper.selectList(new EntityWrapper<Area>());
			map.put("serviceCenter", serviceCenter);
			map.put("instructorList", instructorList);
			map.put("areaList", areaList);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.info("服务中心详情：" + e.getMessage());
		}
		return map;
	}

	@Override
	public int update(ServiceCenter serviceCenter, String path, String[] instructors, String[] levels) {
		// TODO Auto-generated method stub
		try {
			int count = 0;
			List<ServiceCenter> list = serviceCenterMapper.selectList(new EntityWrapper<ServiceCenter>().eq("name", serviceCenter.getName()));
			for (int i = 0; i < list.size(); i++) {
				if (list.get(i).getId() != serviceCenter.getId()) {
					count--;
				}
			}
			if (count >= 0) {
				if (!("").equals(path)) {
					serviceCenter.setImgUrl(path);
				}
				count = serviceCenterMapper.updateById(serviceCenter);
				if (count > 0) {
					for (int i = 0; i < instructors.length; i++) {
						Instructor instructor = new Instructor();
						instructor.setName(instructors[i]);
						instructor.setLevel(levels[i]);
						instructor.setServiceId(serviceCenter.getId());
						int cou = instructorMapper.insertSelective(instructor);
						if (cou > 0) {
							count++;
						}
					}
				}
			}
			return count;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.info("服务中心更新：" + e.getMessage());
			return 0;
		}
	}

	@Override
	public int delete(int id) {
		// TODO Auto-generated method stub
		try {
			int count = serviceCenterMapper.deleteById(id);
			return count;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.info("服务中心删除：" + e.getMessage());
			return 0;
		}
	}

	@Override
	public int updateStatus(int id, int isTop) {
		// TODO Auto-generated method stub
		try {
			ServiceCenter serviceCenter = new ServiceCenter();
			serviceCenter.setId(id);
			serviceCenter.setIsTop(isTop);
			int count = serviceCenterMapper.updateById(serviceCenter);
			return count;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.info("服务中心置顶：" + e.getMessage());
		}
		return 0;
	}

	@Override
	public ResultBean<Map<String, Object>> getList(Double latitude, Double longitude, String name) {
		// TODO Auto-generated method stub
		ResultBean<Map<String, Object>> bean = null;
		Map<String, Object> mapTotal = new HashMap<>();
		List<Markers> list = new ArrayList<>();
		try {
			List<ServiceCenter> sList = serviceCenterMapper.selectList(new EntityWrapper<ServiceCenter>().like("name", name));
			List<Map<String, Object>> mapList = new ArrayList<>();
			for (ServiceCenter sc : sList) {
				Double lat = Double.parseDouble(sc.getLatitude());
				Double lng = Double.parseDouble(sc.getLongitude());
				Double ju = MapUtils.GetDistance(lat, lng, latitude, longitude);
				if (ju <= 5000) {
					Map<String, Object> map = new HashMap<>();
					map.put("id", sc.getId());
					map.put("name", sc.getName());
					map.put("imgUrl", sc.getImgUrl());
					map.put("address", sc.getAddress());
					map.put("ju", ju);
					map.put("mobile", sc.getMobile());
					mapList.add(map);
					Callout out = new Callout();
					out.setContent(sc.getName());
					Markers ma = new Markers();
					ma.setCallout(out);
					ma.setLatitude(lat);
					ma.setLongitude(lng);
					ma.setTitle(sc.getName());
					ma.setId(sc.getId());
					list.add(ma);
				}
			}
			Collections.sort(mapList, new Comparator<Map<String, Object>>() {

				public int compare(Map<String, Object> o1, Map<String, Object> o2) {

					int map1value = (int) Double.parseDouble(o1.get("ju").toString()) * 100;
					int map2value = (int) Double.parseDouble(o2.get("ju").toString()) * 100;
					return map1value - map2value;
				}
			});
			mapTotal.put("mapList", mapList);
			mapTotal.put("marList", list);
			bean = new ResultBean<Map<String, Object>>(mapTotal);
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			bean = new ResultBean<Map<String, Object>>(e);
			logger.info("小程序端服务中心列表：" + e.getMessage());
		}
		return bean;
	}

}
